<?php
  $servername = "localhost";
  $username = "root";
  $password = "zmx093032#";
  $dbname = "bambooredqiming";

  require_once (dirname(__file__) . "/../../include/common.inc.php");
  $gender = $gender == 1 ? '男生' : '女生';
  $name = $name; // 名字
  $fname = cn_substr($name,0); // 姓氏
  $pname = GetPinyin(stripslashes($name)); // 全部拼音
  $pfname = ucfirst(GetPinyin(stripslashes($fname))); // 姓氏对应英文
  $lname = (strlen($name) + mb_strlen($name,'UTF8')) / 2; // 名字长度

  $mname = cn_substr($name,0,1);
  $mpname = ucfirst(GetPinyin(stripslashes($mname)));
  $mpfname = mpname[0];

  // 创建连接
  $conn = new mysqli($servername, $username, $password, $dbname);
  // 检测连接
  if ($conn->connect_error) {
      die("连接失败: " . $conn->connect_error);
  }
  mysqli_query($conn, 'set names utf8');

  $sql = "select * from ded_englishname where gender='$gender' and likechinese like '%$fname%'";

  $result = mysqli_query($conn, $sql);
  if (mysqli_num_rows($result) > 0) {
      // 输出数据
      $resultn = array();
      while($row = mysqli_fetch_assoc($result)) {
          array_push($resultn, $row);
      }

      // var_dump($resultn);
      // 1. 测试是否有相同的中文名

      for ($i = 0, $len = count($resultn); $i < $len; $i++) {
        $englishname = $resultn[$i]['englishname'];
        if ($mpfname == $englishname[0]) {

          echo json_encode(array('code' => '200', 'data' => $resultn[$i]));
          return;
        }
      }

      echo json_encode(array('code' => '200', 'data' => $resultn[rand(0,$len)]));
      // var_dump($resultn);
  } else {

    $sql1 = "select * from ded_englishname where gender='$gender'";
    mysqli_query($conn, 'set names utf8');
    $result1 = mysqli_query($conn, $sql1);
    $resultn1 = array();
    if (mysqli_num_rows($result1) > 0) {
      while($row1 = mysqli_fetch_assoc($result1)) {
          array_push($resultn1, $row1);
      }
      echo json_encode(array('code' => '200', 'data' => $resultn1[rand(0,count($resultn1))]));
    }
  }

  mysqli_close($conn);
?>
